import React, { Component } from 'react'
import {withRouter} from 'react-router-dom'
import {Layout,Modal} from 'antd';

import routers from '../../../router/index'
import LinkButton from '../../../components/link-button'
import reqWeather from '../../../api/weather'
import formateDate from '../../../utils/dateFormat'
import {getUsername,removeUsername,removeToken} from '../../../utils/cookies'
// css
import './index.scss'
const { Header } = Layout;
let interval ;

 class index extends Component {
    state={
        currentTime:formateDate(Date.now()),
        weatherPictureUrl:'',
        weather:''
    }

    componentDidMount(){
      reqWeather().then(res=>{
          this.setState({weather:res.data.now.text,weatherPictureUrl:res.data.now.icon})
      })
       this.getTime()
    }
  
    componentWillUnmount(){
        clearInterval(this.interval)
    }
    getTime=()=>{
        this.interval = setInterval(()=>{
           this.setState({currentTime:formateDate(Date.now())})
        },1000)
    }
    getTitle=()=>{
        const path = this.props.location.pathname
        let title
        // 遍历查找匹配路径 分子路径和父路径
        routers.forEach(item=>{
            if(item.key === path)
                title = item.title
            else if(item.child){
                const cItem = item.child.find(cItem=>path.indexOf(cItem.key)===0)
                if(cItem){
                    title = cItem.title
                }
            }
        })
        return title
    }

    logout=()=>{
        Modal.confirm({
            title:'确认退出吗？',
            okText:"确认",
            cancelText:"取消",
            onOk:()=>{
                // 删除token 跳转到login页面
                removeUsername()
                removeToken()
                this.props.history.replace('')
            }
        })
    }
    render() {
        const {currentTime,weatherPictureUrl,weather}=this.state
        const title=this.getTitle()
        const username = getUsername()
        let url 
        // 为了初次渲染不报错
        weatherPictureUrl?url= `http://192.168.44.83:8881/image/weatherIcon/${weatherPictureUrl}.png`:url={}
        return (
            <Header className="site-layout-background" >
                <div className="header-top" >
                    <span>欢迎，{username}</span>
                    <LinkButton  onClick={this.logout}>退出</LinkButton>
                </div>
                <div className="header-bottom">
                    <div className='header-bottom-left'>{title}</div>
                    <div className='header-bottom-right'>
                        <span>{currentTime}</span>
                        <img src={url} alt="天气预报图片" />
                        <span>{weather}</span>
                    </div>
                </div>
            </Header>

        )
    }
   
}
export default withRouter(index)

